package cn.aj.exm.service.impl;

import cn.aj.exm.domain.MovieTicket;
import cn.aj.exm.domain.User;
import cn.aj.exm.domain.UserMovie;
import cn.aj.exm.exception.GlobalException;
import cn.aj.exm.feign.MovieService;
import cn.aj.exm.feign.UserMovieService;
import cn.aj.exm.mapper.UserMapper;
import cn.aj.exm.result.JsonResult;
import cn.aj.exm.service.IUserService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author GTR
 * @since 2023-01-02
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private MovieService movieService;

    @Autowired
    private UserMovieService userMovieService;

    /**
    * @Title: loadMovieTicket
    * @Description: TODO
    * @Author: Mr.GT
    * @Version: 1.0
    * @Date:  2023/01/2 0002 23:20
    * @Parameters: []
    * @Return cn.aj.exm.result.JsonResult
     * 查询票数
    */
    @Override
    public JsonResult loadMovieTicket() {
        return movieService.list();
    }

    /**
    * @Title: buyTicket
    * @Description: TODO
    * @Author: Mr.GT
    * @Version: 1.0
    * @Date:  2023/01/2 0002 23:21
    * @Parameters: [movieId, count]
    * @Return cn.aj.exm.result.JsonResult
     * 买票
    */
    @Override
    public JsonResult buyTicket(Long movieId, Integer count) {
        JsonResult jsonResult = movieService.get(movieId);
        Object data = jsonResult.getData();
        if(!jsonResult.isSuccess()) {
            return jsonResult;
        }
        // 电影是否存在
        if(data == null) {
            throw new GlobalException("电影已经不存在");
        }
        // 票量是否充足
        MovieTicket movieTicket = JSONObject.parseObject(JSONObject.toJSONString(data), MovieTicket.class);
        Integer stock = movieTicket.getStock();
        if(stock == null || stock < count) {
            throw new GlobalException("电影票库存不足");
        }
        User user = selectById(1L);
        BigDecimal multiply = movieTicket.getPrice().multiply(new BigDecimal(count));
        if(user.getPrice().compareTo(multiply) < 0) {
            throw new GlobalException("您购票余额不足!");
        }
        // 电影是否可以观看
        if(new Date().before(movieTicket.getStartTime())) {
            throw new GlobalException("电影已经结束");
        }
        // 购买电影
        JsonResult buyTicket = movieService.buyTicket(movieId, count);
        if(!buyTicket.isSuccess()) {
           return buyTicket;
        }
        // 购买成功扣余额
        user.setPrice(user.getPrice().subtract(multiply));
        // 修改用户信息
        updateById(user);
        return  JsonResult.success("购票成功!");
    }

    /**
    * @Title: addUser
    * @Description: TODO
    * @Author: Mr.GT
    * @Version: 1.0
    * @Date:  2023/01/3 0003 0:06
    * @Parameters: [user]
    * @Return cn.aj.exm.result.JsonResult
     * 新增用户
    */
    @Override
    public JsonResult addUser(User user) {
        JsonResult list = movieService.list();
        if(!list.isSuccess()) {
            return list;
        }
        List<MovieTicket> movieTickets = JSONObject.parseArray(JSONObject.toJSONString(list), MovieTicket.class);
        Random random = new Random();
        List<MovieTicket> tickets = movieTickets.stream().filter(movieTicket -> movieTicket.getStock() >= 1).collect(Collectors.toList());
        MovieTicket movieTicket = tickets.get(random.nextInt(movieTickets.size()));
        if(movieTicket == null ) {
            throw new GlobalException("无法赠送!");
        }
        // 新增
        insert(user);
        JsonResult jsonResult = movieService.sendMovieTicket(movieTicket.getId(), 1, user.getId());
        if(!jsonResult.isSuccess()) {
            throw new GlobalException("送票成功!");
        }
        return JsonResult.success();
    }

    @Override
    public JsonResult watchMovie(Long movieId, Integer count) {
        JsonResult jsonResult = movieService.get(movieId);
        Object data = jsonResult.getData();
        if(!jsonResult.isSuccess()) {
            return jsonResult;
        }
        // 电影是否存在
        if(data == null) {
            throw new GlobalException("电影已经不存在");
        }
        MovieTicket movieTicket = JSONObject.parseObject(JSONObject.toJSONString(data), MovieTicket.class);
        JsonResult result = userMovieService.userMovieLoadTicket(movieId, 1L);
        Object resultData = result.getData();
        if(!result.isSuccess()) {
            return result;
        }
        UserMovie userMovie = JSONObject.parseObject(JSONObject.toJSONString(resultData), UserMovie.class);
        if(userMovie.getCount() < count) {
            throw new GlobalException("电影票库存不足");
        }
        if(!new Date().before(movieTicket.getEndTime())) {
            throw new GlobalException("电影已经结束观看");
        }
        userMovie.setCount(userMovie.getCount() - count);
        JsonResult orUpdate = userMovieService.saveOrUpdate(userMovie);
        if(!orUpdate.isSuccess()) {
            return jsonResult;
        }
        return JsonResult.success("可以看电影了!");
    }
}
